package daobeauty.interceptor.invoke.impl;

import java.io.Serializable;
import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;

import daobeauty.interceptor.invoke.AbstractCurrentSessionInvokeStrategy;
import daobeauty.util.MethodSignatureUtils;

public class FindByPrimaryKeyInvoke extends AbstractCurrentSessionInvokeStrategy {
	private static final Log LOG = LogFactory.getLog(FindByPrimaryKeyInvoke.class);
	
	@SuppressWarnings("unchecked")
	public FindByPrimaryKeyInvoke(Method method, SessionFactory sessionFactory, Class domainClass, Class<? extends Serializable> primaryKeyClass) {
		super(sessionFactory, domainClass);
		final Class [] parameterTypes = method.getParameterTypes();
		if (parameterTypes==null || parameterTypes.length!=1 || !primaryKeyClass.isAssignableFrom(parameterTypes[0])){
			throw new IllegalArgumentException("method "+MethodSignatureUtils.toMethodSignature(method)+" must have exactly one parameter of type "+primaryKeyClass.getName());
		}
		final Class returnType = method.getReturnType();
		if (!domainClass.isAssignableFrom(returnType)){
			throw new IllegalArgumentException("method "+MethodSignatureUtils.toMethodSignature(method)+" must have return type compatible with "+domainClass.getName());
		}
		if (LOG.isInfoEnabled()){
			LOG.info("created findByPrimaryKey strategy for method "+MethodSignatureUtils.toMethodSignature(method));
		}
	}

	public Object invoke(String methodName, Object[] args) throws Exception {
		if (args==null || args.length<1){
			throw new IllegalArgumentException("\""+methodName+"\" without parameter invoked");
		}
		return getCurrentSession().get(getDomainClass(), (Serializable) args[0]);
	}
}
